﻿Imports System.Data.OleDb

Public Class frmDetailsLocation

    Public locatio As New clsLocation()
    Dim position As Integer

    Public Overloads Function ShowDialog(ByRef lo As clsLocation) As Windows.Forms.DialogResult
        locatio = lo

        afficherVehicule(locatio.vehicule)

        If locatio.noClient <> 0 Then
            remplirInfosClient(locatio.noClient)
        End If

        With locatio
            dptDateDebut.Value = .dateDebut
            dptDateFin.MinDate = .dateDebut
            dptDateFin.Value = .dateFin

            cboModeDePaiement.Text = .modePaiementDepot
            txtNumeroDeCarte.Text = .noCarteDepot
            txtNomSurLaCarte.Text = .nomCarteDepot
        End With

        'load up order defaults
        Return MyBase.ShowDialog()
    End Function

    Sub afficherVehicule(ByVal vehicule As clsVehicule)
        'affiche les options
        lstOptions.Items.Clear()
        For Each opt As clsOptions In vehicule.options
            lstOptions.Items.Add(opt.nom)
        Next

        'remplit le comboBox des catégories
        cboCategories.Items.Clear()
        cboCategories.Items.Add(locatio.vehicule.categorie.nomCategorie)
        cboCategories.Text = locatio.vehicule.categorie.nomCategorie

        'remplit le comboBox des marques
        cboMarque.Items.Clear()
        cboMarque.Items.Add(locatio.vehicule.marque)
        cboMarque.Text = locatio.vehicule.marque

        With vehicule
            'remplit les informations sur le véhicule
            txtNoImmatriculation.Text = .noImmatriculation
            cboCategories.Text = .categorie.nomCategorie
            cboMarque.Text = .marque
            cboModele.Text = .modele
            txtAnnee.Text = .annee
            updValeur.Value = .valeur
            txtKilometrage.Text = .kilometrage
            updNbrPlaces.Value = .nbrPlaces
            txtCapaciteChargement.Text = .capaciteChargement
            cboTransmission.Text = .transmission
            txtCommentaires.Text = .commentaire
            lblPrixVehicule2.Text = .categorie.coutLocationJour

            'actualiser le résumé du véhicule
            lblVehicule.Text = String.Concat(.marque, " ", .modele, " ", .annee)
            lblPrixAssurance.Text = CDbl(.categorie.assurance).ToString("C")
            lblSurchargeKilometrage.Text = CDbl(.categorie.coutSurchargeKm).ToString("C") & "/Km"
            txtDepot.Text = .categorie.prcVoitureDepot / 100 * .valeur + .categorie.montantDepot
            lblSurchargeReservoir.Text = getParam("surchargeReservoir").ToString("C")
            Dim calcul As TimeSpan = dptDateFin.Value - dptDateDebut.Value
            lblPrixVehicule.Text = CDbl(.categorie.coutLocationJour * (Math.Round(calcul.TotalDays) + 1)).ToString("C")
        End With
    End Sub

    Private Sub cboModeDePaiement_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboModeDePaiement.SelectedIndexChanged
        Select Case cboModeDePaiement.Text
            Case "Carte de crédit"
                lblNumeroSurLaCarte.Visible = True
                txtNumeroDeCarte.Visible = True
                lblNomSurLaCarte.Visible = True
                txtNomSurLaCarte.Visible = True
                lblDateExpiration.Visible = True
                dtpDateExpirationCarte.Visible = True

            Case "Carte de débit"
                lblNumeroSurLaCarte.Visible = False
                txtNumeroDeCarte.Visible = False
                lblNomSurLaCarte.Visible = False
                txtNomSurLaCarte.Visible = False
                lblDateExpiration.Visible = False
                dtpDateExpirationCarte.Visible = False

            Case "Comptant"
                lblNumeroSurLaCarte.Visible = False
                txtNumeroDeCarte.Visible = False
                lblNomSurLaCarte.Visible = False
                txtNomSurLaCarte.Visible = False
                lblDateExpiration.Visible = False
                dtpDateExpirationCarte.Visible = False
        End Select

        txtNumeroDeCarte.Clear()
        txtNomSurLaCarte.Clear()

    End Sub

    Private Sub frmNouvelleLocation_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        position = 0
        btnPrecedent.Enabled = False
        btnSuivant.Enabled = True

        'MsgBox("La date minimale de début de location devrait être la date du jour, " & _
        '       "mais nous avons laissé la possibilité de choisir n'importe quelle date afin de pouvoir faire des tests.")

        'cboModeDePaiement.Text = "Comptant"

        'dptDateDebut.Value = Now
        'dptDateFin.Value = dptDateDebut.Value
        'dptDateFin.MinDate = dptDateDebut.Value
        'Dim calcul As TimeSpan = dptDateFin.Value - dptDateDebut.Value
        'lblNbrJours.Text = (Math.Round(calcul.TotalDays) + 1) & " jours(s)"
        'dtpDateExpiration.MinDate = Now
    End Sub

    Private Sub btnPrecedent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrecedent.Click, btnSuivant.Click

        Dim bouton As Button = sender

        Select Case bouton.Text
            Case "Précédent"
                position -= 1

                If position <= 0 Then
                    position = 0
                End If

            Case "Suivant"
                position += 1

                If position >= TabControl1.TabCount - 1 Then
                    position = TabControl1.TabCount - 1
                End If

        End Select

        TabControl1.SelectedTab = TabControl1.TabPages(position)

    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        If TabControl1.SelectedIndex = 0 Then
            btnPrecedent.Enabled = False
        ElseIf TabControl1.SelectedIndex = TabControl1.TabCount - 1 Then
            btnSuivant.Enabled = False
        Else
            btnPrecedent.Enabled = True
            btnSuivant.Enabled = True
        End If
        position = TabControl1.SelectedIndex
    End Sub

    Private Sub btnChercher_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChercher.Click
        recherche = True

        locatio.dateDebut = FormatDateTime(dptDateDebut.Value, DateFormat.ShortDate)
        locatio.dateFin = FormatDateTime(dptDateFin.Value, DateFormat.ShortDate)

        'oblige l'utlisateur à sélectionner un véhicule libre pour les dates spécifiées
        frmGestionVehicules.dtpLibreDu.Checked = True
        frmGestionVehicules.dtpLibreDu.Value = locatio.dateDebut
        frmGestionVehicules.dtpLibreDu.Enabled = False
        frmGestionVehicules.dtpLibreAu.Checked = True
        frmGestionVehicules.dtpLibreAu.Value = locatio.dateFin
        frmGestionVehicules.dtpLibreAu.Enabled = False

        frmGestionVehicules.ShowDialog()

        'If noVehicule <> Nothing Then
        '    lblPrixVehicule2.Text = "45,00"

        '    Dim bdVehicule As New cls_GestionBD("taco.mdb")
        '    'remplit les informations sur le véhicule
        '    bdVehicule.daBd.SelectCommand = New OleDbCommand("SELECT * FROM tblVehicules WHERE noVehicule = @noVehicule")
        '    bdVehicule.daBd.SelectCommand.Parameters.Add("@noVehicule", OleDbType.Integer).Value = noVehicule

        '    bdVehicule.remplirDataSet("tblVehicule")

        '    With bdVehicule.dsBd.Tables("tblVehicule").Rows(0)
        '        txtNoImmatriculation.Text = .Item("noImmatriculation")
        '        cboMarque.Text = nvl(.Item("marque"), "")
        '        cboModele.Text = nvl(.Item("modele"), "")
        '        txtAnnee.Text = nvl(.Item("annee"), "")
        '        updValeur.Value = nvl(.Item("valeur"), 0)
        '        txtKilometrage.Text = nvl(.Item("kilometrage"), 0)
        '        updNbrPlaces.Value = nvl(.Item("nbrPlaces"), 0)
        '        txtCapaciteChargement.Text = nvl(.Item("capaciteChargement"), 0)
        '        cboTransmission.Text = nvl(.Item("transmission"), "")
        '        txtCommentaires.Text = nvl(.Item("commentaire"), "")

        '        'actualise le résumé de la location
        '        lblVehicule.Text = String.Concat(nvl(.Item("marque"), ""), " ", nvl(.Item("modele"), ""), " ", nvl(.Item("annee"), ""))
        '    End With

        '    Dim bdCategories As New cls_GestionBD("taco.mdb")
        '    bdCategories.daBd.SelectCommand = New OleDbCommand("SELECT * FROM tblCategories WHERE noCategorie = @noCategorie")
        '    bdCategories.daBd.SelectCommand.Parameters.Add("@noCategorie", OleDbType.VarChar, 15).Value = bdVehicule.dsBd.Tables("tblVehicule").Rows(0).Item("noCategorie")
        '    bdCategories.remplirDataSet("tblCategorie")

        '    With bdCategories.dsBd.Tables("tblCategorie").Rows(0)
        '        cboCategories.Text = nvl(.Item("nomCategorie"), "")
        '        'actualise le résumé de la location

        '        lblPrixAssurance.Text = CDbl(nvl(.Item("assurance"), 0)).ToString("C")
        '        lblSurchargeKilometrage.Text = CDbl(nvl(.Item("coutSurchargeKm"), 0)).ToString("C") & "/Km"
        '        txtDepot.Text = .Item("prcVoitureDepot") / 100 * nvl(bdVehicule.dsBd.Tables("tblVehicule").Rows(0).Item("valeur"), 0) + .Item("montantDepot")
        '    End With

        '    lblSurchargeReservoir.Text = getParam("surchargeReservoir").ToString("C")
        '    Dim calcul As TimeSpan = dptDateFin.Value - dptDateDebut.Value
        '    lblPrixVehicule.Text = CDbl(45 * (Math.Round(calcul.TotalDays) + 1)).ToString("C")

        '    Dim bd As New cls_GestionBD("taco.mdb")
        '    bd.daBd.SelectCommand = New OleDbCommand("SELECT nomOption FROM tblOptions WHERE noOption IN( " & _
        '                                             "SELECT noOption FROM tblOptionsVehicules WHERE noVehicule IN( " & _
        '                                             "SELECT noVehicule FROM tblVehicules WHERE noVehicule = @noVehicule ))")
        '    bd.daBd.SelectCommand.Parameters.Add("@noVehicule", OleDbType.VarChar).Value = bdVehicule.dsBd.Tables("tblVehicule").Rows(0).Item("noVehicule")
        '    bd.remplirDataSet("tblOptions")

        '    lstOptions.Items.Clear()

        '    For Each element As DataRow In bd.dsBd.Tables("tblOptions").Rows
        '        lstOptions.Items.Add(element.Item(0))
        '    Next
        'End If
    End Sub

    Private Sub dptDateDebut_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dptDateDebut.ValueChanged, dptDateFin.ValueChanged
        Dim dpt As DateTimePicker = sender
        'MsgBox("test2")

        If dpt.Name = "dptDateDebut" Then
            's'assure que la date de fin sera après la date de début
            dptDateFin.MinDate = dptDateDebut.Value
            dptDateFin.Value = dptDateDebut.Value
        End If

        dtpDateExpirationCarte.MinDate = FormatDateTime(dptDateFin.Value, DateFormat.ShortDate)
        dtpDateExpirationCarte.Value = FormatDateTime(dptDateFin.Value, DateFormat.ShortDate)
        dtpDateExpirationCarte.MinDate = FormatDateTime(dptDateFin.Value, DateFormat.ShortDate)

        'actualise le résumé de la location
        lblDateDebut.Text = dptDateDebut.Value.ToString("D")
        lblDateFin.Text = dptDateFin.Value.ToString("D")
        Dim calcul As TimeSpan = dptDateFin.Value - dptDateDebut.Value
        lblNbrJours.Text = (Math.Round(calcul.TotalDays) + 1) & " jours(s)"
        lblPrixVehicule.Text = CDbl(locatio.vehicule.categorie.coutLocationJour * (Math.Round(calcul.TotalDays) + 1)).ToString("C")

    End Sub

    Private Sub btnChercherClient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChercherClient.Click
        saisie = True
        frmGestionClients.ShowDialog(True)

        If idClient <> Nothing Then
            remplirInfosClient(idClient)
            locatio.noClient = idClient
        End If
    End Sub

    Sub remplirInfosClient(ByVal idClient As Integer)
        Dim bdClient As New cls_GestionBD("taco.mdb")
        bdClient.daBd.SelectCommand = New OleDbCommand("SELECT  commentaire, codePostal as CodePostal, CodeProvince as CodeProvince, noPermisConduire as noPermisConduire, nom AS Nom, prenom AS Prenom, dateNaissance as DateDeNaissance, adresse as Adresse, " & _
    "ville as Ville, telephone as Telephone, accidentDerniereAnnee as Accident, responsable as Responsable, typeClient as TypeClient, noEntreprise as noEntreprise,personneContact as Personne, postePersonneContact as Poste, courriel as Courriel, NAS as NAS, cellulaire as Cell, actif as Actif, noClient " _
   & "FROM tblClients where noClient =  @noClient")
        bdClient.daBd.SelectCommand.Parameters.Add("@noClient", OleDbType.Integer).Value = idClient
        bdClient.remplirDataSet("tblClients")

        For Each colonne As DataColumn In bdClient.dsBd.Tables("tblClients").Columns
            'For i = 0 To dsClients.Tables("tblClients").Columns.Count
            '    MsgBox(dsClients.Tables("tblClients").Rows(0).Item(i))
            'Next
            With bdClient.dsBd.Tables("tblClients").Rows(0)
                Select Case colonne.ColumnName
                    Case "noPermisConduire"
                        txtNoPermisConduire.Text = nvl(.Item("noPermisConduire"), "")
                    Case "CodePostal"
                        lblClientCodePostal.Text = nvl(.Item("CodePostal"), "")
                    Case "Nom"
                        txtNom.Text = nvl(.Item("Nom"), "")
                        lblClientNom.Text = nvl(.Item("Prenom"), "") & " " & nvl(.Item("Nom"), "")
                    Case "Cell"
                        txtCell.Text = nvl(.Item("Cell"), "")
                    Case "Prenom"
                        txtPrenom.Text = nvl(.Item("Prenom"), "")
                    Case "DateDeNaissance"
                        dtNaiss.Value = nvl(.Item("DateDeNaissance"), "")
                        'dtNaiss.Value = CDate("2-2-2009")
                        txtAge.Text = calcul_age(dtNaiss.Value)
                    Case "Adresse"
                        txtAdresse.Text = nvl(.Item("Adresse"), "")
                        lblClientAdresse.Text = nvl(.Item("Adresse"), "")
                    Case "CodeProvince"
                        remplirListCbo("province", cboProvince.Text, cboProvince, "")
                        cboProvince.Text = getProvince(nvl(.Item("CodeProvince"), ""))

                    Case "Ville"
                        cboVille.Text = nvl(.Item("Ville"), "")
                        remplirListCbo("ville", cboVille.Text, cboVille, " WHERE v.CodeProvince = p.CodeProvince AND p.nomProvince = '" & cboProvince.SelectedItem & "'")
                        lblClientVille.Text = nvl(.Item("Ville"), "") & ", " & getProvince(nvl(.Item("CodeProvince"), ""))
                    Case "Courriel"
                        txtCourriel.Text = nvl(.Item("Courriel"), "")
                    Case "Telephone"
                        txtTel.Text = nvl(.Item("Telephone"), "")
                    Case "NAS"
                        txtNas.Text = nvl(.Item("NAS"), "")
                    Case "Accident"

                        If nvl(.Item("Accident"), "false") = "True" Then
                            optOuiAccident.Checked = True
                        Else
                            optNonAccident.Checked = True
                            panResponsable.Enabled = False
                        End If
                    Case "Responsable"

                        If nvl(.Item("Responsable"), "false") = "True" Then
                            optOuiResponsable.Checked = True
                        Else
                            optNonResponsable.Checked = True
                        End If
                    Case "TypeClient"
                        'le client doit avoir un type, sinon ça bug
                        cboTypeClient.Text = nvl(.Item("TypeClient"), "")

                        If Not IsDBNull(bdClient.dsBd.Tables("tblClients").Rows(0).Item("noEntreprise")) Then
                            Dim dbEntreprises = New cls_taco

                            dbEntreprises.defDataset("SELECT noEntreprise,nom,telephone,adresse,CodeProvince,ville,codepostal,actif,commentaire from tblEntreprises where noEntreprise = " & nvl(bdClient.dsBd.Tables("tblClients").Rows(0).Item("noEntreprise"), 0) & ";", "tblEntreprises")

                            For Each colonne2 As DataColumn In dbEntreprises.ds.Tables("tblEntreprises").Columns

                                With dbEntreprises.ds.Tables("tblEntreprises")
                                    Select Case colonne2.ColumnName

                                        Case "nom"
                                            txtNomEntreprise.Text = nvl(.Rows(0).Item("nom"), "")
                                        Case "adresse"
                                            txtAdresseEntreprise.Text = nvl(.Rows(0).Item("adresse"), "")
                                        Case "codepostal"
                                            txtCodePostal.Text = nvl(.Rows(0).Item("codepostal"), "")
                                        Case "commentaire"
                                            txtCommentaire.Text = nvl(.Rows(0).Item("commentaire"), "")
                                        Case "CodeProvince"
                                            Dim codeProvince As String
                                            codeProvince = nvl(.Rows(0).Item("CodeProvince"), "")
                                            cboProvinceEntreprise.Text = getProvince(codeProvince)
                                        Case "ville"
                                            cboVilleEntreprise.Text = nvl(.Rows(0).Item("ville"), "")

                                        Case "telephone"
                                            txtTelephoneEntreprise.Text = nvl(.Rows(0).Item("Telephone"), "")
                                    End Select
                                End With
                            Next
                            TxtContact.Text = nvl(.Item("Personne"), "")
                            txtPoste.Text = nvl(.Item("Poste"), "")
                        End If
                End Select
            End With
        Next
    End Sub

    Private Sub btnTerminer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTerminer.Click

        With locatio

            If .vehicule.noVehicule <> 0 AndAlso .noClient <> 0 Then

                If validerAccidentsClient(.noClient) AndAlso validerListeNoirClient(.noClient) Then

                    .dateDebut = FormatDateTime(dptDateDebut.Value, DateFormat.ShortDate)
                    .dateFin = FormatDateTime(dptDateFin.Value, DateFormat.ShortDate)

                    .nbrKmDepart = .vehicule.kilometrage

                    .montantDepot = txtDepot.Text
                    .modePaiementDepot = cboModeDePaiement.Text
                    .noCarteDepot = txtNumeroDeCarte.Text
                    .nomCarteDepot = txtNomSurLaCarte.Text
                    .dateExpirationCarteDepot = dtpDateExpirationCarte.Value

                    .enregistrer()
                    frmGestionLocations.btnChercher.PerformClick()
                    Me.Close()
                End If

            Else
                MsgBox("Vous devez sélectionner un véhicule et un client pour terminer la location.", MsgBoxStyle.Exclamation)
            End If

        End With

        'Dim bdLocations As New cls_GestionBD("taco.mdb")
        'bdLocations.remplirDataSet("SELECT * FROM tblLocations WHERE noLocation = null", "tblLocation")

        'Dim lNewRow As DataRow
        'lNewRow = bdLocations.dsBd.Tables("tblLocation").NewRow

        'With lNewRow
        '    .Item("noLocation") = createNewNo("noLocation", "tblLocations")
        '    .Item("noVehicule") = noVehicule
        '    .Item("noClient") = idClient
        '    .Item("dateDebut") = dptDateDebut.Value
        '    .Item("dateFinLocation") = dptDateFin.Value
        '    .Item("nbrKmDepart") = txtKilometrage.Text
        '    .Item("montantDepot") = txtDepot.Text
        '    .Item("modePaiementDepot") = cboModeDePaiement.Text
        '    .Item("noCarteDepot") = txtNumeroDeCarte.Text
        '    .Item("dateExpirationCarteDepot") = dtpDateExpiration.Value
        '    .Item("actif") = True
        'End With

        'bdLocations.dsBd.Tables("tblLocation").Rows.Add(lNewRow)

        'bdLocations.miseAJourBD("tblLocation")
        'frmGestionLocations.btnChercher.PerformClick()
        'Me.Close()

    End Sub

    Private Function validerAccidentsClient(ByVal noClient As Integer) As Boolean

        Dim commande As New OleDbCommand
        commande.CommandText = _
            "SELECT COUNT(*) AS nbrAccidents, MAX(dateAccident) AS dateDernierAccident " & _
            "FROM tblAccidents " & _
            "WHERE noClient = @noClient"
        commande.Parameters.Add("@noClient", OleDbType.Integer).Value = noClient

        Dim bd As New cls_GestionBD("taco.mdb")
        bd.remplirDataSet(commande, "tblAccidents")

        Dim nbrAccidents As Integer = bd.dsBd.Tables("tblAccidents").Rows(0).Item("nbrAccidents")

        If nbrAccidents > getParam("nbMentionDommagePourRefus") Then
            MsgBox("Le client a plus de " & getParam("nbMentionDommagePourRefus") & " accidents à son actif, la location est refusée.", MsgBoxStyle.Exclamation)
            Return False
        ElseIf nbrAccidents = 0 Then
            Return True
        Else

            Dim dateDernierAccident As Date = bd.dsBd.Tables("tblAccidents").Rows(0).Item("dateDernierAccident")

            Dim calcul As TimeSpan = Now - dateDernierAccident
            Dim nbrJours As Integer = Math.Round(calcul.TotalDays) + 1

            If nbrJours <= getParam("jourExemptAccident") Then
                MsgBox("Le client a eu un accident il y a moins de " & getParam("jourExemptAccident") & " jours, la location est refusée.", MsgBoxStyle.Exclamation)
                Return False
            Else
                Return True
            End If

        End If

    End Function

    Private Function validerListeNoirClient(ByVal noClient As Integer) As Boolean

        Dim commande As New OleDbCommand
        commande.CommandText = _
            "SELECT COUNT(*) AS nbrEntrees " & _
            "FROM tblListeNoire " & _
            "WHERE noClient = @noClient AND dateDebut + duree >= @dateDuJour"
        commande.Parameters.Add("@noClient", OleDbType.Integer).Value = noClient
        commande.Parameters.Add("@dateDuJour", OleDbType.DBDate).Value = FormatDateTime(Now, DateFormat.ShortDate)

        Dim bd As New cls_GestionBD("taco.mdb")
        bd.remplirDataSet(commande, "tblListNoire")

        Dim nbrEntrees As Integer = bd.dsBd.Tables("tblListNoire").Rows(0).Item("nbrEntrees")

        If nbrEntrees >= 1 Then
            MsgBox("Le client est sur la liste noire, il est donc impossible de lui faire une location", MsgBoxStyle.Exclamation)
            Return False
        Else
            Return True
        End If

    End Function

    Private Sub frmDetailsLocation_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        Me.Dispose()
    End Sub
End Class